<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="入库单编号" prop="sn">
        <el-input
          v-model="queryParams.sn"
          placeholder="请输入入库单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['procurementmanagement:entry:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['procurementmanagement:entry:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['procurementmanagement:entry:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="entryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="入库单编号" align="center" prop="sn" width="180px" />
      <el-table-column label="入库日期" align="center" prop="entryTime" width="100px">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.entryTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属部门" align="center" prop="deptName" />
      <el-table-column label="供应商" align="center" prop="supplierName" />
      <el-table-column label="仓库" align="center" prop="warehouseName" />
      <el-table-column label="经手人" align="center" prop="handledByName" />
      <el-table-column label="车牌号" align="center" prop="plateNumber" />
      <el-table-column label="审核人" align="center" prop="auditBy" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === '未提交'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['procurementmanagement:entry:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.status === '未提交'"
            size="mini"
            type="text"
            icon="el-icon-upload"
            @click="handleSubmit(scope.row)"
            v-hasPermi="['procurementmanagement:entry:submit']"
          >提交</el-button>
          <el-button
            v-if="scope.row.status === '已提交'"
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleWithdraw(scope.row)"
            v-hasPermi="['procurementmanagement:entry:withdraw']"
          >撤回</el-button>
          <el-button
            v-if="scope.row.status === '已提交'"
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleAudit(scope.row)"
            v-hasPermi="['procurementmanagement:entry:audit']"
          >审核</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['procurementmanagement:entry:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改入库单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="入库单编号" prop="sn" >
          <el-input v-model="form.sn" placeholder="请输入入库单编号" style="width: 220px"  disabled/>
        </el-form-item>
        <el-form-item label="入库时间" prop="entryTime">
          <el-date-picker clearable
                          v-model="form.entryTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择入库时间" @change="handleDateChange">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="供应商名称" prop="supplierName">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleSupplierDialog"
          > {{ form.supplierName || '请选择供应商' }}</el-button>
        </el-form-item>

        <el-form-item label="所属部门">
          <el-cascader
            v-model="form.deptId"
            :options="deptTree"
            :props="{ checkStrictly: true, value: 'id', label: 'name' }"
            placeholder="请选择所属部门"
            @change="handleDeptChange">
          </el-cascader>
        </el-form-item>

        <el-form-item label="仓库名称" prop="warehouseId">
          <el-select
            v-model="form.warehouseId"
            placeholder="请选择仓库名称"
            clearable
            @change="handleWarehouseChange"
          >
            <el-option
              v-for="warehouse in warehouseOptions"
              :key="warehouse.id"
              :label="warehouse.name"
              :value="warehouse.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="经手人">
          <el-cascader
            v-model="form.handledById"
            :options="personList"
            :props="{ checkStrictly: true, value: 'id', label: 'realName' }"
            placeholder="请选择编制人"
            @change="handleCreatorChange">
          </el-cascader>
        </el-form-item>
        <el-form-item label="车牌号" prop="plateNumber">
          <el-input v-model="form.plateNumber" style="width: 220px" placeholder="请输入车牌号" />
        </el-form-item>
        <el-form-item label="相关合同" prop="purchasePlanId">
          <el-button
            @click="handleProcurementPlanDialog"
            style="background-color: blue; color: white;"
          > 选择</el-button>{{ form.contractSn || '请选择相关合同' }}
        </el-form-item>


        <el-form-item label="关联计划" prop="procurementPlanSn">
          <el-input v-model="form.procurementPlanSn" style="width: 220px" placeholder="请输入采购计划编号" />
        </el-form-item>

        <h3>入库单明细</h3>
        <el-table :data="entryGoods" border style="width: 100%; margin-bottom: 20px">
          <el-table-column prop="goodsId" label="商品ID" width="120" v-if="false"></el-table-column>
          <el-table-column prop="goodsSn" label="商品编号" width="120"></el-table-column>
          <el-table-column prop="goodsName" label="商品名称" width="150"></el-table-column>
          <el-table-column prop="categoryId" label="分类ID" width="120" v-if="false"></el-table-column>
          <el-table-column prop="categoryName" label="商品分类" width="120"></el-table-column>
          <el-table-column prop="specification" label="规格型号" width="120"></el-table-column>
          <el-table-column prop="unit" label="单位" width="80"></el-table-column>
          <el-table-column prop="price" label="单价" width="100">
            <template slot-scope="scope">
              <el-input v-model.number="scope.row.price" @change="calculateItemTotal(scope.$index)"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="num" label="数量" width="100">
            <template slot-scope="scope">
              <el-input v-model.number="scope.row.num" @change="calculateItemTotal(scope.$index)"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="taxRate" label="税率(%)" width="100">
            <template slot-scope="scope">
              <el-input v-model.number="scope.row.taxRate" @change="calculateItemTotal(scope.$index)"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="subtotal" label="税前合计" width="120">
            <template slot-scope="scope">
              {{ scope.row.subtotal ? scope.row.subtotal.toFixed(2) : '0.00' }}
            </template>
          </el-table-column>
          <el-table-column prop="totalPrice" label="含税合计" width="120"></el-table-column>
        </el-table>
=======
          <el-table :data="entryGoods" border style="width: 100%; margin-bottom: 20px">
            <el-table-column prop="goodsId" label="商品ID" width="120" v-if="false"></el-table-column>
            <el-table-column prop="goodsSn" label="商品编号" width="120"></el-table-column>
            <el-table-column prop="goodsName" label="商品名称" width="150"></el-table-column>
            <el-table-column prop="categoryId" label="分类ID" width="120" v-if="false"></el-table-column>
            <el-table-column prop="categoryName" label="商品分类" width="120"></el-table-column>
            <el-table-column prop="specification" label="规格型号" width="120"></el-table-column>
            <el-table-column prop="unit" label="单位" width="80"></el-table-column>
            <el-table-column prop="price" label="单价" width="100">
              <template slot-scope="scope">
                <el-input v-model.number="scope.row.price" @change="calculateItemTotal(scope.$index)"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="num" label="数量" width="100">
              <template slot-scope="scope">
                <el-input v-model.number="scope.row.num" @change="calculateItemTotal(scope.$index)"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="taxRate" label="税率(%)" width="100">
              <template slot-scope="scope">
                <el-input v-model.number="scope.row.taxRate" @change="calculateItemTotal(scope.$index)"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="subtotal" label="税前合计" width="120">
              <template slot-scope="scope">
                {{ scope.row.subtotal ? scope.row.subtotal.toFixed(2) : '0.00' }}
              </template>
            </el-table-column>
            <el-table-column prop="totalPrice" label="含税合计" width="120"></el-table-column>
          </el-table>
>>>>>>> master

        <!-- 新增总合计显示 -->
        <div class="total-summary">
          <span class="total-label">税前合计：</span>
          <span class="total-amount">{{ subtotalAmount.toFixed(2) }}</span>
          <span class="total-label" style="margin-left: 20px;">含税合计：</span>
          <span class="total-amount">{{ totalAmount.toFixed(2) }}</span>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 供应商选择器弹出窗口 -->
    <el-dialog :visible.sync="supplierDialogVisible" title="选择供应商" width="1000px">
      <el-table :data="supplierList">
        <el-table-column label="选择" width="55">
          <template slot-scope="scope">
            <el-radio
              v-model="selectedSupplierId"
              :label="scope.row.id"
              @change="handleSupplierRadioChange(scope.row)"
              class="custom-radio"
            ></el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="customName" label="供应商名称"></el-table-column>
        <el-table-column prop="customSn" label="供应商编码"></el-table-column>
        <el-table-column prop="productionAddress" label="地址"></el-table-column>
        <el-table-column prop="transfer" label="传真"></el-table-column>
        <el-table-column prop="linkman" label="联系人"></el-table-column>
        <el-table-column prop="telephone" label="电话"></el-table-column>
        <el-table-column prop="email" label="电子邮件"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="supplierDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSupplierSelection">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="planListDialogVisible" title="选择相关合同">
      <el-table
        :data="planList"
        @row-click="handlePlanListRowClick"
        highlight-current-row
        ref="planTable"
        current-row-key="id" >
        <el-table-column type="radio" width="55" />
        <el-table-column prop="sn" label="合同编号"></el-table-column>
        <el-table-column prop="supplierName" label="供应商"></el-table-column>
        <el-table-column prop="signTime" label="签订日期"></el-table-column>
        <el-table-column prop="contractStatus" label="合同状态"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="planListDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPlanSelection">确定</el-button>
      </div>
    </el-dialog>

    <!-- 相关合同选择器弹出窗口 -->
    <el-dialog :visible.sync="planListDialogVisible" title="选择相关合同" width="1000px">
      <el-table :data="planList">
        <el-table-column label="选择" width="55">
          <template slot-scope="scope">
            <el-radio
              v-model="selectedContractId"
              :label="scope.row.id"
              @change="handleContractRadioChange(scope.row)"
              class="custom-radio"
            ></el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="sn" label="合同编号"></el-table-column>
        <el-table-column prop="supplierName" label="供应商"></el-table-column>
        <el-table-column prop="signTime" label="签订日期"></el-table-column>
        <el-table-column prop="contractStatus" label="合同状态"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelContractSelection">取消</el-button>
        <el-button type="primary" @click="confirmContractSelection">确定</el-button>
      </div>
    </el-dialog>

    <!-- 审核弹窗 -->
    <el-dialog :visible.sync="auditDialogVisible" title="审核入库单" width="600px">
      <el-form :model="auditForm" label-width="100px">
        <el-form-item label="入库单编号">
          <el-input v-model="auditForm.sn" :disabled="true" />
        </el-form-item>
        <el-form-item label="入库时间">
          <el-input v-model="auditForm.entryTime" :disabled="true" />
        </el-form-item>
        <el-form-item label="仓库">
          <el-input v-model="auditForm.warehouseName" :disabled="true" />
        </el-form-item>
        <el-form-item label="供应商">
          <el-input v-model="auditForm.supplierName" :disabled="true" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleReject">审核驳回</el-button>
        <el-button type="primary" @click="confirmAudit">审核通过</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listEntry, getEntry, delEntry, addEntry, updateEntry } from "@/api/procurementmanagement/entry";
import {
  getCompiler,
  getDeptTree, getPlan,
  getSupplierList,
  getsupplierListBid, listPlan,
} from "@/api/procurementmanagement/plan";
import {listContract ,getContract,getContractProducts } from "@/api/procurementmanagement/contract";
import { listWarehouse } from "@/api/system/warehouse";

export default {
  name: "Entry",
  data() {
    return {
      subtotalAmount: 0,  // 税前总合计金额
      totalAmount: 0,     // 含税总合计金额
      entryGoods: [], // 入库单明细数据
      selectedSupplierId: null,
      selectedContractId: null,
      selectedContract: null,
      // 仓库选项
      warehouseOptions: [],
      auditDialogVisible: false,
      // 部门表格数据
      systemDeptList: [],
      //二级部门
      deptTree: [],
      //制表人
      personList:[],
      supplierDialogVisible: false,
      planListDialogVisible: false,
      selectedSupplier: null,
      //供应商
      supplierList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      planList: [],
      // 入库单表格数据
      entryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      auditForm: {
        id: '',
        sn: '', // 入库单编号
        entryTime: '', // 入库时间
        warehouseName: '', // 仓库名称
        supplierName: '', // 供应商名称
      },
      // 查询参数
      queryParams: {
        warehouseName:null,
        pageNum: 1,
        pageSize: 10,
        sn: null,
        supplierId: null,
        deptId: null,
        warehouseId: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getWarehouseOptions();
  },
  methods: {
    handleWarehouseChange(warehouseId) {
      const selectedWarehouse = this.warehouseOptions.find(warehouse => warehouse.id === warehouseId);
      if (selectedWarehouse) {
        this.form.warehouseName = selectedWarehouse.name;
      }
    },
    /** 查询入库单列表 */
    getList() {
      this.loading = true;
      listEntry(this.queryParams).then(response => {
        this.entryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      // 重置入库单明细数据和总合计金额
      this.entryGoods = [];
      this.totalAmount = 0;
      this.cancelContractSelection();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        sn: null,
        entryTime: null,
        supplierId: null,
        supplierSn: null,
        deptId: null,
        warehouseId: null,
        deptName: null,
        supplierName: null,
        warehouseName: null,
        contractId: null,
        handledById: null,
        handledByName: null,
        plateNumber: null,
        purchasePlanId: null,
        deliveryNumber: null,
        contractAttachment: null,
        auditBy: null,
        status: null,
        auditRemark: null,
        procurementPlanSn: null,
        contractSn: null,
        supplierSettlementFlag: null,
        supplierSettlementId: null,
        createTime: null,
        updateTime: null,
        creator: null,
        updater: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 获取仓库列表 */
    getWarehouseOptions() {
      listWarehouse().then(response => {
        response.rows.forEach(warehouse => {
          warehouse.warehouseName = warehouse.name;
        });
        this.warehouseOptions = response.rows;
      });
    },
    handlePlanListRowClick(row) {
      this.selectedContract = row;
      this.selectedContractId = row.id;
      this.$refs.planTable.setCurrentRow(row);
    },
    confirmContractSelection() {
      if (this.selectedContract) {
        getContract(this.selectedContract.id).then(response => {
          const contractData = response.data;
          this.form.contractSn = contractData.sn; // 合同编号
          this.form.contractId = contractData.id; // 合同ID

          // 自动填充关联计划编号
          this.form.procurementPlanSn = contractData.procurementPlanSn ||
            contractData.planSn ||
            contractData.relatedPlanSn ||
            ''; // 根据实际数据结构调整

          // 如果合同中有供应商信息，也可以自动填充
          if (contractData.supplierName && !this.form.supplierName) {
            this.form.supplierName = contractData.supplierName;
            this.form.supplierId = contractData.supplierId;
          }

          // 如果合同有产品，加载产品信息
          if (this.selectedContract.id) {
            this.getContractProducts(this.selectedContract.id);
          }

          this.planListDialogVisible = false;
          this.$message.success("合同选择成功");
        }).catch(error => {
          console.error("获取合同详情失败", error);
          this.$message.error("获取合同详情失败");
        });
      } else {
        this.$message.warning("请选择一个合同");
      }
    },
    getContractProducts(contractId) {
      getContractProducts(contractId).then(response => {
        this.entryGoods = response.data.map(item => ({
          goodsId: item.goodsId, // 商品ID
          goodsSn: item.goodsSn,
          goodsName: item.goodsName,
          categoryId: item.categoryId, // 分类ID
          categoryName: item.categoryName, // 分类名称
          specification: item.specification,
          unit: item.unit,
          price: item.price,
          num: item.num,
          taxRate: item.taxRate,
          subtotal: item.price * item.num,
          totalPrice: (item.price * item.num) * (1 + (item.taxRate / 100))
        }));
        this.calculateTotalAmount();
      });
    },
=======
            this.planListDialogVisible = false;
            this.$message.success("合同选择成功");
          }).catch(error => {
            console.error("获取合同详情失败", error);
            this.$message.error("获取合同详情失败");
          });
        } else {
          this.$message.warning("请选择一个合同");
        }
      },
        getContractProducts(contractId) {
          getContractProducts(contractId).then(response => {
            this.entryGoods = response.data.map(item => ({
              goodsId: item.goodsId, // 商品ID
              goodsSn: item.goodsSn,
              goodsName: item.goodsName,
              categoryId: item.categoryId, // 分类ID
              categoryName: item.categoryName, // 分类名称
              specification: item.specification,
              unit: item.unit,
              price: item.price,
              num: item.num,
              taxRate: item.taxRate,
              subtotal: item.price * item.num,
              totalPrice: (item.price * item.num) * (1 + (item.taxRate / 100))
            }));
            this.calculateTotalAmount();
          });
        },
>>>>>>> master
    // 提交操作
    handleSubmit(row) {
      this.$modal.confirm('是否确认提交入库单编号为"' + row.sn + '"的数据项？').then(() => {
        return updateEntry({ ...row, status: '已提交' }); // 更新状态为已提交
      }).then(() => {
        this.$modal.msgSuccess("提交成功");
        this.getList(); // 刷新列表
      }).catch(() => {});
    },

    // 取消选择合同
    cancelContractSelection() {
      this.selectedContractId = null;
      this.selectedContract = null;
      this.planListDialogVisible = false;
    },

    // 撤回操作
    handleWithdraw(row) {
      this.$modal.confirm('是否确认撤回入库单编号为"' + row.sn + '"的数据项？').then(() => {
        return updateEntry({ ...row, status: '未提交' }); // 更新状态为未提交
      }).then(() => {
        this.$modal.msgSuccess("撤回成功");
        this.getList(); // 刷新列表
      }).catch(() => {});
    },

    // 审核操作
    handleAudit(row) {
      this.auditForm = {
        id: row.id, // 确保传入入库单 ID
        sn: row.sn, // 入库单编号
        entryTime: row.entryTime, // 入库时间
        warehouseName: row.warehouseName, // 仓库名称
        supplierName: row.supplierName, // 供应商名称
        auditRemark: row.auditRemark || '', // 审核意见
      };
      this.auditDialogVisible = true; // 打开审核弹窗
    },

    // 审核驳回操作
    handleReject() {
      this.$modal.confirm('是否确认驳回入库单编号为"' + this.auditForm.sn + '"的数据项？').then(() => {
        const now = new Date();
        const formattedDate = now.toLocaleString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }).replace(/\//g, '-');

        console.log("Sending update request with data:", {
          id: this.auditForm.id,
          sn: this.auditForm.sn,
          status: '未提交',
          updateTime: formattedDate
        });

        return updateEntry({
          id: this.auditForm.id, // 确保传入入库单 ID
          sn: this.auditForm.sn, // 确保传入入库单编号
          status: '未提交', // 更新状态为“未提交”
          updateTime: formattedDate // 格式化后的时间
        });
      }).then(() => {
        this.$modal.msgSuccess("审核驳回成功");
        this.auditDialogVisible = false; // 关闭弹窗
        this.getList(); // 刷新列表
      }).catch(error => {
        console.error("审核驳回失败", error);
        this.$modal.msgError("审核驳回失败，请检查网络或联系管理员");
      });
    },

    // 审核通过操作
    confirmAudit() {
      this.$modal.confirm(
        '是否确认审核通过入库单编号为"' + this.auditForm.sn + '"的数据项？'
      ).then(() => {
        return updateEntry({
          ...this.auditForm,
          status: "审核通过",
          auditBy: "superadmin",
        }); // 更新状态为审核通过，审核人为 superadmin
      }).then(() => {
        this.$modal.msgSuccess("审核通过成功");
        this.auditDialogVisible = false; // 关闭弹窗
        this.getList(); // 刷新列表
      }).catch(() => {});
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getDeptTree(); // 获取部门树
      this.getCompiler(); // 获取编制人
      // 获取当前日期作为默认签订时间
      const now = new Date();
      const entryTime = now.toISOString().slice(0, 10); // 格式化为 YYYY-MM-DD
      this.form.entryTime = entryTime;

      // 根据签订时间生成合同编号
      this.generateContractNumber(entryTime);
      this.open = true;
      this.title = "添加入库单";
    },
    // 处理日期变化事件
    handleDateChange(date) {
      if (date) {
        this.generateContractNumber(date); // 生成新的入库单编号
      }
    },
    generateContractNumber(entryTime) {
      const prefix = "RKD"; // 编号前缀
      const formattedDate = entryTime.replace(/-/g, ""); // 将日期格式化为 YYYYMMDD
      let seq = 1; // 默认序列号为 1

      // 假设从后端获取当天的合同数量
      this.getContractCountByDate(entryTime).then(count => {
        seq = count + 1; // 当天的合同数量加1
        const formattedSeq = String(seq).padStart(4, "0"); // 序列号格式化为 0001
        this.form.sn = `${prefix}${formattedDate}${formattedSeq}`; // 拼接编号
      });
    },
    getContractCountByDate(date) {
      // 调用后端接口获取当天的合同数量
      return new Promise((resolve, reject) => {
        // 示例：调用后端接口
        listContract({ entryTime: date }).then(response => {
          resolve(response.total); // 返回当天的合同数量
        }).catch(error => {
          console.error("获取合同数量失败", error);
          resolve(0); // 如果失败，默认返回0
        });
      });
    },

    handleContractRadioChange(row) {
      this.selectedContract = row;
      this.selectedContractId = row.id;
    },

    // 计算单项商品的合计金额
    calculateItemTotal(index) {
      const item = this.entryGoods[index];
      if (item.price && item.num && item.taxRate) {
        // 计算税前金额
        item.subtotal = item.price * item.num;
        // 计算税额
        const taxAmount = item.subtotal * (item.taxRate / 100);
        // 计算含税合计
        item.totalPrice = item.subtotal + taxAmount;
        // 更新总合计
        this.calculateTotalAmount();
      }
    },

    // 计算所有商品的总合计金额
    calculateTotalAmount() {
      this.subtotalAmount = this.entryGoods.reduce((total, item) => {
        return total + (item.subtotal || 0);
      }, 0);
      this.totalAmount = this.entryGoods.reduce((total, item) => {
        return total + (item.totalPrice || 0);
      }, 0);
    },
    // 修改确认选择方法
    confirmPlanSelection() {
      if (this.selectedplan) {
        getContract(this.selectedplan.id).then(response => {
          const contractData = response.data;
          this.form.contractSn = contractData.sn; // 合同编号
          this.form.contractId = contractData.id; // 合同ID

          // 自动填充采购计划编号（根据您的实际数据结构调整）
          this.form.procurementPlanSn = contractData.procurementPlanSn ||
            contractData.planSn ||
            contractData.relatedPlanSn ||
            '';

          // 如果合同中有供应商信息，也可以自动填充
          if (contractData.supplierName && !this.form.supplierName) {
            this.form.supplierName = contractData.supplierName;
            this.form.supplierId = contractData.supplierId;
          }

          this.planListDialogVisible = false;
          this.$message.success("合同选择成功，相关信息已自动填充");
        }).catch(error => {
          console.error("获取合同详情失败", error);
          this.$message.error("获取合同详情失败");
        });
      } else {
        this.$message.warning("请选择一个合同");
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getEntry(id).then(response => {
        this.form = response.data;
        this.getDeptTree(); // 获取部门树
        this.getCompiler(); // 获取编制人
        this.open = true;
        this.title = "修改入库单";
      });
    },

    // 获取执行中的合同列表
    listContract() {
      listContract({
        pageSize: 1000,
        contractStatus: '执行中'  // 只查询执行中的合同
      }).then(response => {
        this.planList = response.rows;
      });
    },

    // 获取部门树
    getDeptTree() {
      getDeptTree().then(response => {
        console.log(response.data)
        this.deptTree = response.data;
      });
    },
    //获取编制人
    getCompiler(){
      getCompiler().then(response => {
        this.personList = response.data;
      })
    },
    // 修改采购计划对话框为合同对话框
    handleProcurementPlanDialog() {
      this.listContract();  // 调用获取合同列表的方法
      this.planListDialogVisible = true;
    },
    listPlan(){
      listPlan(this.queryParams).then(response => {
        this.planList = response.rows;
        this.total = response.total;
      });
    },
    // 打开供应商选择器
    handleSupplierDialog(){
      this.getSupplierList();
      this.supplierDialogVisible = true;
    },

// 获取供应商列表
    getSupplierList() {
      getSupplierList().then(response => {
        this.supplierList = response.data;
      });
    },

// 处理供应商行点击事件
    handleSupplierRowClick(row) {
      this.selectedSupplier = row; // 保存当前选中的供应商
    },
    handleSupplierRadioChange(row) {
      this.selectedSupplier = row;
      this.selectedSupplierId = row.id; // 手动设置选中的供应商ID
    },
    // 确认选择供应商
    confirmSupplierSelection() {
      if (this.selectedSupplier) {
        this.form.supplierName = this.selectedSupplier.customName;
        this.form.supplierId = this.selectedSupplier.id;
        this.supplierDialogVisible = false;
      } else {
        this.$message.warning("请选择一个供应商");
      }
    },
    handleCreatorChange(value) {
      if (value.length > 0) {
        // 获取选中项的最后一个值作为 id
        const selectedPerson = this.personList.find(person => person.id.toString() === value[value.length - 1].toString());
        if (selectedPerson) {
          this.form.handledById = selectedPerson.id; // 保存编制人 ID 到表单
          this.form.handledByName = selectedPerson.realName; // 保存编制人名称到表单
          console.log(this.form.handledByName,this.form.handledById);
        }
      } else {
        this.form.handledById = null;
        this.form.handledByName = null;
      }
    },
    handleDeptChange(value) {
      if (value.length > 0) {
        // 获取选中的最后一级部门的 ID
        const deptId = value[value.length - 1];
        // 根据 ID 查找对应的部门对象
        const selectedDept = this.findDeptById(this.deptTree, deptId);
        if (selectedDept) {
          this.form.deptId = selectedDept.id; // 保存子部门的 ID
          this.form.deptName = selectedDept.name; // 保存子部门的名称
          console.log(this.form.deptName,this.form.deptId);
        }
      } else {
        this.form.deptId = null;
        this.form.deptName = null;
      }
    },
// 根据 ID 查找部门对象
    findDeptById(tree, id) {
      for (let dept of tree) {
        if (dept.id === id) {
          return dept; // 如果找到匹配的 ID，返回该部门对象
        }
        if (dept.children && dept.children.length > 0) {
          const result = this.findDeptById(dept.children, id); // 递归查找子部门
          if (result) return result;  // 如果在子部门中找到，返回结果
        }
      }
      return null; // 如果未找到，返回 null
    },

    /** 提交按钮 */
    submitForm() {
      // 构建入库单数据
      const entryData = {
        ...this.form,
        entryProducts: this.entryGoods.map(item => ({
          goodsId: item.goodsId, // 确保包含商品ID
          goodsSn: item.goodsSn,
          goodsName: item.goodsName,
          categoryId: item.categoryId, // 确保包含分类ID
          categoryName: item.categoryName, // 确保包含分类名称
          specification: item.specification,
          unit: item.unit,
          price: item.price,
          num: item.num,
          taxRate: item.taxRate,
          subtotal: item.subtotal,
          totalPrice: item.totalPrice
        }))
      };

      // 发送入库单数据到后端
      addEntry(entryData).then(response => {
        if (response.code === 200) {
          this.$message.success("入库单添加成功");
          this.open = false;
          this.reset();
          this.getList();
          this.cancel();
        } else {
          this.$message.error("入库单添加失败", response.msg);
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除入库单编号为"' + ids + '"的数据项？').then(function() {
        return delEntry(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('procurementmanagement/entry/export', {
        ...this.queryParams
      }, `entry_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
/* 完全隐藏单选按钮的所有标签内容 */
.custom-radio ::v-deep .el-radio__label {
  display: none !important;
  width: 0;
  height: 0;
  overflow: hidden;
}

.total-summary {
  text-align: right;
  margin-top: 10px;
  font-size: 16px;
  font-weight: bold;
}

.total-label {
  margin-right: 10px;
}

.total-amount {
  color: #f56c6c;
}

/* 覆盖 Element UI 单选框的 aria-hidden 样式 */
.el-radio__original {
  aria-hidden: unset !important;
  /* 可以考虑添加 inert 属性 */
  /* inert: true; */
}
</style>
